package com.surrey.p2p.controller;

import java.util.List;
import java.util.Random;

import com.surrey.p2p.model.CANNode;
import com.surrey.p2p.model.HopCount;
import com.surrey.p2p.model.P2PNode;
import com.surrey.p2p.model.Point;
import com.surrey.p2p.view.Network;

/**
 * Controller for the peer to peer network. Will allow creation and manipulation
 * of nodes.
 * 
 * @author Vedika Dalmia
 * 
 */

public class P2PController {
	


	public static void main(String[] args) throws Exception {

		// create network
		Network network = new Network();
		XMLInputReader xir = new XMLInputReader("resources/NetworkComplex.xml");
		List<P2PNode> nodes = xir.getCANNodes();
		for (P2PNode node : nodes) {
			node.addObserver(network);
			node.makeLive();
		}
		System.out.println("Starting lookup");
		
		
		Random r = new Random();
	
	
			int hopCountSum=0;
			int numOfRuns=1000;
		for (int i = 0; i < numOfRuns; i++) {
			Point p = new Point(r.nextDouble(), r.nextDouble());
			CANNode c = (CANNode) nodes.get(r.nextInt(nodes.size()));
			//System.out.println("Looking for " + p + " starting at " + c.getAddress());	
			HopCount count=new HopCount();
			CANNode result = c.lookup(p,count);
			result.finishRouting();
			//System.out.println(count.getHopCount());
			hopCountSum+=count.getHopCount();
			//System.out.println("Found the result at " + result.getAddress());
		}
		System.out.println("Average Hop Count" + (double)hopCountSum/((double)numOfRuns));

		
		
		//Code to test a single routing scenario
		/*
		double x=1.8,y=0.0;
		int nodeNum=0;
		Point p = new Point(x,y);
		CANNode c = (CANNode) nodes.get(nodeNum);
		System.out.println("Looking for " + p + " starting at " + c.getAddress());	
		HopCount count=new HopCount();
		CANNode result = c.lookup(p,count);
		result.finishRouting();
		System.out.println(count.getHopCount());
		System.out.println("Found the result at " + result.getAddress());
		*/
		

	}

}
